package SocketLearn.NetSocketLearn;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-06 16:16
 * @description URL网络编程
 * 1.URL:统一资源定位符
 * 2.格式：
 *  http://localhost:8080/xxxx/xxxx？xx=yy
 *  协议    主机名     端口  资源地址   参数列表
 *
 *
 *
 */
public class URLTest {
    public static void main(String[] args) {
        try {
            URL url=new URL("http://localhost:8080/examples/tiyala.jpg");
//            System.out.println(url.getProtocol());
//            System.out.println(url.getHost());
//            System.out.println(url.getPort());
//            System.out.println(url.getPath());
//            System.out.println(url.getFile());
//            System.out.println(url.getQuery());

            //从tomcat服务器获取资源
            InputStream is=null;
            FileOutputStream fos=null;
            URLConnection urlConnection=null;
            HttpURLConnection httpURLConnection=null;
            try {
                urlConnection= url.openConnection();
                httpURLConnection=(HttpURLConnection)urlConnection;

                httpURLConnection.connect();
                is= urlConnection.getInputStream();
                String path="D:\\Java Learn\\IOLearnTestFile\\picturetest\\tomcatget.jpg";
                fos=new FileOutputStream(path);

                byte[] buffer =new byte[1024];
                int len;
                while((len=is.read(buffer))!=-1){
                    fos.write(buffer,0,len);
                }
                System.out.println("完成！");

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(is!=null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fos!=null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }

            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }
}
